package internal

import (
	"fmt"
	"github.com/gin-gonic/gin"
	"net/http"
	"text/template"
	"ylhtest01/internal/core/app"
	"ylhtest01/internal/core/usecase"
)

type statusHtmlData struct {
	AppVersion  string
	NumContacts int
}

// StatusHtmlHandler renders status.html template
// Feel free to remove this function and entire file if you are not
// planning to use go templates with HTML files
func StatusHtmlHandler(uc *usecase.UseCases) func(c *gin.Context) {
	t := template.Must(template.ParseFiles("web/static/status_tpl.html"))
	return func(c *gin.Context) {
		contacts, err := uc.LoadAddrBookContacts(c.Request.Context())
		if err != nil {
			c.JSON(http.StatusInternalServerError, NewInternalServerErrResponse(err))
			return
		}
		data := statusHtmlData{
			AppVersion:  fmt.Sprintf("%s %s (%s)", AppVersion.Service, AppVersion.Version, AppVersion.Build),
			NumContacts: len(contacts),
		}
		if err = t.Execute(c.Writer, data); err != nil {
			app.Logger(c.Request.Context()).Panicln("error executing template", err)
			c.JSON(http.StatusInternalServerError, NewInternalServerErrResponse(err))
		}
		return
	}
}
